package com.regvision.contacts.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.regvision.contacts.R;
import com.regvision.contacts.domain.ContactDataModel;
import com.regvision.contacts.main.ContactsApplication;
import com.regvision.contacts.ui.adapter.EMailAdapter;
import com.regvision.contacts.ui.adapter.PhoneAdapter;
import com.regvision.contacts.widget.CircleImageView;

public class ContactActivity extends BaseActivity implements OnClickListener {
	
	protected static final String TAG = "ContactActivity";
	
	public static final String INTENT_CONTACT = "intent_contact";
	
	private ContactDataModel model;
	
	private LinearLayout llPhone;
	private LinearLayout llMail;
	
	private ListView mPhoneView;
	private ListView mEMailView;
	
	private PhoneAdapter mPhoneAdapter;
	private EMailAdapter mEMailAdapter;
	
	private CircleImageView mImgHead;
	private TextView mTvName;
	
	private ContactsApplication mContactsApplication;
	private List<String> channelList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contact);
		
		findView();
		initData();
		initView();
	}
	
	
	private void findView() {
		mTvName = (TextView) findViewById(R.id.tv_contact_name);
		mImgHead = (CircleImageView) findViewById(R.id.img_contact_head);
		llPhone = (LinearLayout) findViewById(R.id.ll_contact_phone);
		llMail = (LinearLayout) findViewById(R.id.ll_contact_mail);
		mPhoneView = (ListView) findViewById(R.id.lv_contact_phone);
		mEMailView = (ListView) findViewById(R.id.lv_contact_email);
		
		Button btnShare = (Button) findViewById(R.id.btnShare);
		btnShare.setOnClickListener(this);
	}
	
	private void initData() {
		try {
			model = (ContactDataModel) getIntent().getSerializableExtra(INTENT_CONTACT);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (model == null) {
			model = new ContactDataModel();
		}

		mPhoneAdapter = new PhoneAdapter(getContext(), R.layout.item_phone, model.phones);
		mEMailAdapter = new EMailAdapter(getContext(), R.layout.item_email, model.emails);
		
		// 没有任何号码
		if (model.phones.size() == 0) {
			llPhone.setVisibility(View.GONE);
		} 
		// 没有任何EMail
		if (model.emails.size() == 0) {
			llMail.setVisibility(View.GONE);
		} 
		
		mContactsApplication = (ContactsApplication)getApplication();
		
		channelList = new ArrayList<String>();
	}
	
	private void initView() {
		mTvName.setText(model.name);
		mPhoneView.setAdapter(mPhoneAdapter);
		mEMailView.setAdapter(mEMailAdapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.contact, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_about:
            	openActivity(AboutActivity.class);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
			case R.id.btnShare: {
				String[] arrChannels = getChannelList(mContactsApplication.getFoundChannels());
				if (arrChannels != null)
					showChannelListDialog(arrChannels);
				else
					Toast.makeText(ContactActivity.this, "未发现Alljoyn设备", Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
		}
	}
    
    private void showChannelListDialog(String[] arrChannels) {
    	 AlertDialog.Builder builder = new AlertDialog.Builder(ContactActivity.this);
         builder.setTitle("选择要分享的Alljoyn设备");
         builder.setItems(arrChannels, new DialogInterface.OnClickListener()
         {
             @Override
             public void onClick(DialogInterface dialog, int which)
             {
            	 System.out.println(channelList.get(which));
            	 doJoinSession(channelList.get(which));
            	 doShareContactInfo();
            	 doLeaveSession();
             }
         });
         
         builder.show();
     }

    private String[] getChannelList(List<String> newChannelList) {
    	
    	String[] arrChannels = null;
    	
    	channelList.clear();
    	for (String channel : newChannelList) {
    		if (!channel.contains(mContactsApplication.hostGetChannelName()))
    			channelList.add(channel);
    	}
    	
    	if (channelList.size() > 0) {
    		arrChannels = new String[channelList.size()];
        	for (int i = 0; i < channelList.size(); i++) {
        		String[] arrStr = channelList.get(i).split("-");
        		arrChannels[i] = arrStr[arrStr.length-1];
        	}
    	}
		
		return arrChannels;
	}
    
    private void doJoinSession(String channel) {
		mContactsApplication.useSetChannelName(channel);
		mContactsApplication.useJoinChannel();
	}
    
    private void doShareContactInfo() {
    	new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				System.out.println(model.toJson());
				mContactsApplication.doUseSendMessage(model.toJson());
			}
		}, 800);
    }
    
    private void doLeaveSession() {
    	
    	new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				mContactsApplication.useLeaveChannel();
			}
		}, 1500);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
}
